package com.zr.interceptor;

import com.alibaba.fastjson.JSON;
import com.zr.utils.AjaxResult;
import com.zr.utils.RedisUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录认证拦截器
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    @Resource
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(!StringUtils.hasLength(token) || redisUtil.get(token) == null){
            response.setContentType("text/html;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            //返回JSON
            PrintWriter out = response.getWriter();
            out.write(JSON.toJSONString(AjaxResult.fail(401, "用户未登录", null)));
            out.flush();
            return false;
        }else{
            //更新过期时间
            redisUtil.set(token, redisUtil.get(token), 150L, TimeUnit.MINUTES);
        }
        return true;
    }
}
